import { UserGroupEntity } from './../../entities/userGroup.entity';
import { GroupEntity } from './../../entities/group.entity';
import { GroupMessageEntity } from '../../entities/groupMessage.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';

@Injectable()
export class GroupService {
  constructor(
    @InjectRepository(GroupEntity)
    private readonly groupRepository: Repository<GroupEntity>,
    @InjectRepository(UserGroupEntity)
    private readonly userGroupRepository: Repository<UserGroupEntity>,
    @InjectRepository(GroupMessageEntity)
    private readonly groupMessageRepository: Repository<GroupMessageEntity>,
  ) {}

  // 获取用户所有的群
  async getUserGroups(user_id: string) {
    const groupList = await this.userGroupRepository.find({user_id: user_id});
    return groupList;
  }

  // 获取多个群信息
  async getGroups(group_ids: string) {
    let groupIdArr = group_ids.split(',');
    let groupArr = [];
    for (let group_id of groupIdArr) {
      let group = await this.groupRepository.findOne({id: group_id});
      groupArr.push(group);
    }
    return groupArr;
  }

  // 获取单个群成员
  async getGroupUsers(group_id: string) {
    const groupUserList = await this.userGroupRepository.find({group_id: group_id});
    return groupUserList;
  }

  // 获取单个群消息
  async getGroupMessage(group_id: string) {
    const groupMessage = await this.groupMessageRepository.find({group_id: group_id});
    return groupMessage;
  }

  // 模糊搜索群信息
  async getGroupByName(name: string) {
    const groups = await this.groupRepository.find({name: Like(`%${name}%`)});
    return groups;
  }
}
